package com.zfei.gfb.controller;

import cn.hutool.core.date.DateUtil;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.gson.JsonObject;
import com.zfei.gfb.api.StatsService;
import com.zfei.gfb.api.domain.StatsTag;
import com.zfei.gfb.api.domain.StatsValue;
import com.zfei.gfb.bean.Const;
import com.zfei.gfb.bean.DataMap;
import com.zfei.gfb.bean.Status;
import com.zfei.gfb.bean.StatusException;
import com.zfei.gfb.core.Auth;
import com.zfei.gfb.core.HttpJson;
import com.zfei.gfb.core.LogResult;
import com.zfei.gfb.dao.GfbGoodsMapper;
import com.zfei.gfb.dao.GfbUserMapper;
import com.zfei.gfb.dao.GfbVillagerMapper;
import com.zfei.gfb.device.AppContext;
import com.zfei.gfb.model.GfbGoods;
import com.zfei.gfb.model.GfbJob;
import com.zfei.gfb.model.GfbUser;
import com.zfei.gfb.model.GfbVillager;
import com.zfei.gfb.query.GfbGoodsQuery;
import com.zfei.gfb.request.GfbDelRequest;
import com.zfei.gfb.request.GfbGetRequest;
import com.zfei.gfb.request.GfbGoodsAddRequest;
import com.zfei.gfb.util.Beans;
import com.zfei.gfb.util.Gsons;
import com.zfei.gfb.util.Now;
import com.zfei.gfb.util.gson.Types;
import com.zfei.gfb.vo.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @author
 * @version 1.0
 */
@Auth(type = {Const.VILLAGE_MANAGER, Const.TOWN_MANAGER})
@Api(tags = "乡村集市管理接口")
@RestController
@RequestMapping("/web/goods")
public class GfbGoodsController {

    @Resource
    private GfbGoodsMapper gfbGoodsMapper;

    @Resource
    private HttpSession httpSession;

    @Resource
    private StatsService statsService;

    @Resource
    private GfbVillagerMapper gfbVillagerMapper;

    @ApiOperation(value = "后台物品发布")
    @ApiResponses({
            @ApiResponse(code = 200, message = "", response = GfbGoodsVo.class),
    })
    @LogResult
    @HttpJson("/add")
    public Object add(@RequestBody GfbGoodsAddRequest request) {

        request.checkInsertNull();
        if (request.getUserId() == null) {
            throw new StatusException(Status.INVALID_ARGUMENT);
        }
        GfbGoods record = Beans.copy(request, GfbGoods.class);

        GfbVillager villager = gfbVillagerMapper.selectByPrimaryKey(request.getUserId());
        if (villager == null) {
            throw new StatusException(Status.NOT_EXIST);
        }

        record.setImages(Gsons.toJson(request.getImages()));
        record.setUserId(villager.getId());
        record.setVillagerName(villager.getVillagerName());
        record.setStatus(Const.GOOD_ON);
        record.setPubTime(Now.millis());
        record.setCreateTime(Now.millis());
        record.setUpdateTime(Now.millis());
        record.setCntime(DateUtil.now());

        Map<String, String> ext = Maps.newHashMap();
        ext.put("from", "admin");
        record.setExt(Gsons.toJson(ext));

        gfbGoodsMapper.insertSelective(record);


        GfbGoodsVo vo = Beans.copy(record, GfbGoodsVo.class);
        return vo;
    }

    @ApiOperation(value = "列表")
    @ApiResponses({
            @ApiResponse(code = 200, message = "", response = GfbGoodsListVo.class),
    })
    @LogResult
    @HttpJson("/list")
    public Object list(@RequestBody GfbGoodsQuery query) {
        query.check().build(Now::millis);

        GfbGoodsListVo result = new GfbGoodsListVo();

        int total = gfbGoodsMapper.total(query);
        result.setTotal(total);
        if (total == 0) {
            result.setData(Lists.newArrayList());
            return result;
        }

        List<GfbGoods> list = gfbGoodsMapper.list(query);

        List<GfbGoodsVo> vos = new ArrayList<>();
        for (GfbGoods item : list) {
            GfbGoodsVo vo = Beans.copy(item, GfbGoodsVo.class);
            List<String> images = Gsons.fromJson(item.getImages(), Types.StringListType);

            vo.setImages(images);
            vo.setBrowseNum(statsService.get(item.getId().toString(), StatsTag.GOODS_BROWSE_COUNT).getNum());
            vos.add(vo);
        }

        result.setData(vos);

        return result;

    }

    @ApiOperation(value = "删除")
    @LogResult
    @HttpJson("/del")
    public Object del(@RequestBody GfbDelRequest req) {
        req.checkDelNull();
        Integer id = req.getId();

        if (id == null) {
            throw new StatusException(Status.INVALID_ARGUMENT);
        }

        GfbGoods record = gfbGoodsMapper.selectByPrimaryKey(id);
        if (record == null) {
            throw new StatusException(Status.NOT_EXIST);
        }

        gfbGoodsMapper.deleteByPrimaryKey(id);
        return null;
    }

    @ApiOperation(value = "详情")
    @ApiResponses({
            @ApiResponse(code = 200, message = "", response = GfbGoodsVo.class),
    })
    @LogResult
    @HttpJson("/get")
    public Object get(@RequestBody GfbGetRequest request) {
        request.checkGetNull();
        Integer id = request.getId();

        GfbGoods record = gfbGoodsMapper.selectByPrimaryKey(id);

        GfbGoodsVo vo = Beans.copy(record, GfbGoodsVo.class);
        List<String> images = Gsons.fromJson(record.getImages(), Types.StringListType);
        vo.setImages(images);

        GfbVillager goodsOwner = gfbVillagerMapper.selectByPrimaryKey(record.getUserId());
        vo.setOwner(goodsOwner.getName());
        vo.setVillager(goodsOwner);

        String ext = record.getExt();

        String from;
        if (StringUtils.isBlank(ext)) {
            from = "client";
        } else {
            JsonObject jsonObject = Gsons.parseJsonObject(ext);
            if (jsonObject.has("from")) {
                from = jsonObject.get("from").getAsString();
            } else {
                from = "client";
            }
        }

        vo.setFrom(from);
        return vo;
    }

}
